import socket
import threading


class ConnectedBasket:
    def __init__(self) -> None:
        self._pool = {}
        pass
    
    def addConnector(self, c_):
        self._pool[id(c_)] = c_
    
    def getConnector(self, c_):
        ret = []
        for i in self._pool:
            if i != id(c_):
                ret.append(self._pool[i])
        return ret
    
    def removeConnector(self, c_):
        self._pool.pop(id(c_))


class Connthr(threading.Thread):
    def __init__(self, c: socket.SocketType, bsk: ConnectedBasket):
        super().__init__()
        self._c: socket.SocketType = c
        self._basket: ConnectedBasket = bsk
        
        
    
    def run(self) -> None:
        self._c.settimeout(1.0)
        try:
            get = self._c.recv(64)
        except:
            self._c.close()
            return
        if get == b'1122443':
            self._c.settimeout(None)
            self._basket.addConnector(self._c)
            while True:
                get = self._c.recv(1024)
                if len(get) == 0:
                    break
                print('recv:', get)
                send = self._basket.getConnector(self._c)
                for i in send:
                    i.send(get)
            self._basket.removeConnector(self._c)
        self._c.close()


def main():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    basket = ConnectedBasket()
    s.bind(('0.0.0.0', 1899))
    s.listen(5)
    while True:
        c, addr = s.accept()
        print('accept:', addr)
        con = Connthr(c, basket)
        con.start()
        


if __name__ == "__main__":
    main()
